package com.cosytek.farmmanager;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.cosytek.farmmanager.data.Farm;
import com.cosytek.farmmanager.data.Main;
import com.cosytek.farmmanager.data.Task;

import org.w3c.dom.Text;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link TaskFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TaskFragment extends Fragment implements View.OnClickListener, ServerRequest.IServerRequestListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String PATH_START_TASK = "/startTask";
    private static final String PATH_STOP_TASK = "/stopTask";
    // TODO: Rename and change types of parameters
    private String farmId;
    private String taskId;

    private Activity parent;

    private OnFragmentInteractionListener mListener;

    private TextView viewTaskName;
    private TextView viewOwnerFarm;
    private TextView viewTaskType;
    private TextView viewTaskStatus;
    private TextView viewTaskDescription;
    private Button viewTaskAction;
    private View mProgressForm;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment TaskFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static TaskFragment newInstance(String param1, String param2) {
        TaskFragment fragment = new TaskFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public TaskFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            farmId = getArguments().getString(ARG_PARAM1);
            taskId = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_task, container, false);

        viewTaskName = (TextView)view.findViewById(R.id.frag_task_name);
        viewOwnerFarm = (TextView)view.findViewById(R.id.frag_task_belong_farm);
        viewTaskType = (TextView)view.findViewById(R.id.frag_task_type);
        viewTaskStatus = (TextView)view.findViewById(R.id.frag_task_status);
        viewTaskDescription = (TextView)view.findViewById(R.id.frag_task_description);

        viewTaskAction = (Button)view.findViewById(R.id.frag_task_btn_start_stop);
        viewTaskAction.setOnClickListener(this);
        mProgressForm = view.findViewById(R.id.common_progress_form);
        refreshUI();
        return view;
    }

    private void refreshUI() {
        Task t = getTask();
        if (t == null) return;

        viewTaskName.setText(t.getName());
        viewTaskType.setText(t.getType());
        viewTaskDescription.setText(t.getDescription());
        viewOwnerFarm.setText(t.getFarmName());
        viewTaskStatus.setText(t.getStatus());
    }

    private Task getTask() {
        MainActivity ma = (MainActivity)parent;
        Main main = ma.getMain();

        Farm f = main.getFarm(farmId);
        if (f == null) {
            return null;
        }

        Task t = f.getTaskById(taskId);
        if (t == null) {
            return null;
        }
        return t;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(this, uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
            parent = activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
        parent = null;
    }

    public void updateTask(String farmId, String taskId) {
        this.farmId = farmId;
        this.taskId = taskId;

        refreshUI();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.frag_task_btn_start_stop:
                Task t = getTask();
                if (t.getStatus() == "start") {
                    stopTask();
                } else {
                    startTask();
                }
                break;
        }
    }

    private void startTask() {
        mProgressForm.setVisibility(View.VISIBLE);

        String token = ((MainActivity)parent).getToken();
        ServerRequest request = ServerRequest.newGetRequest(this, token, String.format("%s?fid=%s&tid=%s",PATH_START_TASK, farmId, taskId));
        request.setTag("task");
        request.execute();
    }

    private void stopTask() {
        mProgressForm.setVisibility(View.VISIBLE);

        String token = ((MainActivity)parent).getToken();
        ServerRequest request = ServerRequest.newGetRequest(this, token, String.format("%s?fid=%s&tid=%s",PATH_STOP_TASK, farmId, taskId));
        request.setTag("task");
        request.execute();
    }

    @Override
    public void onRequestCompleted(ServerRequest r, boolean success, ServerError error, String respBody) {
        mProgressForm.setVisibility(View.GONE);
        if (parent == null) {
            return;
        }

        if (success) {
            String tag = r.tag();
            switch (tag) {
                case "task":
                    break;
            }

            return;
        }

        if (error != null) {
            UIHelper.promptError(parent, error);
        }
    }
}
